// 防抖
const creatDebounce = (delay = 1000) => {
    let timer = null
    return fn => {
        clearTimeout(timer)
        timer = setTimeout(() => {
            fn && fn()
        }, delay);
    }
}

// 节流
const creatThrottle = (delay = 1000) => {
    let status = "START"
    return fn => {
        if (status === "START") {
            status = "WAITING"
            setTimeout(() => {
                fn && fn()
                status = "START"
            }, delay);
        }
    }
}

export default class debounce_throttle_plugin {
    static install(Vue) {
        Vue.mixin({
            created() {
                if (typeof this.onReachBottom === "function") {
                    const throttle = creatThrottle()
                    window.addEventListener("scroll", () => {
                        const offsetHeight = document.documentElement.offsetHeight
                        const screenHeight = window.screen.height
                        const scrollY = window.scrollY
                        const gap = offsetHeight - screenHeight - scrollY
                        if (gap < 50) {
                            throttle(this.onReachBottom)
                        }
                    })
                };
            },
            methods: {
                creatDebounce
            },
        })
    }
}